package com.hnkywl.sts.service.sys;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.dao.sys.YgDao;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.interceptor.AuthInterceptor;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.Md5;
import com.hnkywl.sts.util.ReflectionUtils;
import com.opensymphony.xwork2.ActionContext;
import net.ruixin.orm.hibernate.Page;
import org.hibernate.tool.hbm2x.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 说明：
 * 包:        com.hnkywl.sts.service.sys
 * 类描述:    员工服务类
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Service
public class YgService {

    private YgDao ygDao;

    private GsjgDao gsjgDao;

    /**
     * 查询员工列表
     *
     * @param mc       员工名称
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Transactional
    public String findAllYg(Long sjjgId, String mc, String gh, String dlm, Date rzsygtart, Date rzsjEnd, String cwbh, int pageNo, int pageSize) {
        Page<Yg> ygPage = this.ygDao.findYgList(sjjgId, mc, gh, dlm, rzsygtart, rzsjEnd, cwbh, pageNo, pageSize);
        List<Yg> ygList = ygPage.getResult() == null ? new ArrayList<Yg>() : ygPage.getResult();
        String ygJson = BaseUtils.fetchCollectionToJson(ygList, "id", "gh", "dlm", "xm", "zgjg.qc", "zggs.jc", "zygw.mc", "kdl", "sfzz", "cwbh", "rzsj", "dhhm", "zssj.xm", "cxfw", "kmdm");
        return "{\"total\":" + ygPage.getTotalCount() + ",\"rows\":[" + ygJson + "]}";
    }


    @Transactional
    public List<Yg> findAllYgforExport(Long sjjgId, String mc, String gh, String dlm, Date rzsygtart, Date rzsjEnd, String cwbh, int pageNo, int pageSize) {
        Page<Yg> ygPage = this.ygDao.findYgList(sjjgId, mc, gh, dlm, rzsygtart, rzsjEnd, cwbh, pageNo, pageSize);
        List<Yg> ygList = ygPage.getResult() == null ? new ArrayList<Yg>() : ygPage.getResult();
        return ygList;
    }

    @Transactional
    public String findAllYgByXmGs(String xm, Long gsId, int pageNo, int pageSize) {
        Page<Yg> ygPage = this.ygDao.findAllYgByXmGs(xm, gsId, pageNo, pageSize);
        List<Yg> ygList = ygPage.getResult() == null ? new ArrayList<Yg>() : ygPage.getResult();
        List<Map> grid = new ArrayList<Map>();
        for (Yg yg : ygList) {
            Map item = new HashMap();
            item.put("yg.id", yg.getId());
            item.put("yg.xm", yg.getXm());
            item.put("zgjgJc", yg.getZggs() == null ? null : yg.getZggs().getJc());
            item.put("yg.jqdlm", yg.getJqdlm());
            item.put("yg.jqdlmm", yg.getJqdlmm());
            grid.add(item);
        }
        return "{\"total\":" + ygPage.getTotalCount() + ",\"rows\":" + new Gson().toJson(grid) + "}";
    }


    //员工姓名列表显示
    @Transactional
    public String findYgXm(String ygxm, int pageNo, int pageSize) {
        Page<Yg> ygPage = this.ygDao.findYgXmList(ygxm, pageNo, pageSize);
        List<Yg> ygList = ygPage.getResult() == null ? new ArrayList<Yg>() : ygPage.getResult();
        String ygJson = BaseUtils.fetchCollectionToJson(ygList, "id", "xm");
        return "[" + ygJson + "]";
    }

    @Transactional
    public String SearchFromId(Long id) {
        Yg yg = this.ygDao.get(id);
        List<Yg> ygList = new ArrayList<Yg>();
        ygList.add(yg);
        String ygJson = BaseUtils.fetchCollectionToJson(ygList, "id", "xm");
        return "[" + ygJson + "]";
    }

    /**
     * 科目代码映射
     *
     * @param sjjgId
     * @param mc
     * @param pageNo
     * @param pageSize
     * @return
     */
    public String findKmdm(Long sjjgId, String mc, int pageNo, int pageSize) {
        Page<Yg> ygPage = this.ygDao.findYgList(sjjgId, mc, null, null, null, null, null, pageNo, pageSize);
        List<Yg> ygList = ygPage.getResult() == null ? new ArrayList<Yg>() : ygPage.getResult();
        List<Map> grid = new ArrayList<Map>();
        for (Yg yg : ygList) {
            Map item = new HashMap();
            item.put("yg.id", yg.getId());
            item.put("yg.xm", yg.getXm());
            item.put("zggsQc", yg.getZggs() == null ? null : yg.getZggs().getQc());
            item.put("zgjgJc", yg.getZgjg() == null ? null : yg.getZgjg().getJc());
            item.put("yg.kmdm", yg.getKmdm());
            grid.add(item);
        }
        return "{\"total\":" + ygPage.getTotalCount() + ",\"rows\":" + new Gson().toJson(grid) + "}";
    }

    @Transactional
    public List findYgListByGs(Long zgjgId) {
        List list = this.ygDao.findYgListByZgjg(zgjgId);
        return list;
    }

    @Transactional
    public List findYgListByGsGw(Long zggsId, Long gwId) {
        List list = this.ygDao.findYgListByZggsGw(zggsId, gwId);
        return list;
    }

    @Transactional
    public String findYgListByZgjg(Long zgjgId) {
        Gson gson = new Gson();
        List list = this.ygDao.findYgListByZgjg(zgjgId);
        return gson.toJson(list);
    }

    @Transactional
    public String findAllYgListByZgjg(Long zgjgId) {
        Gson gson = new Gson();
        List list = this.ygDao.findAllYgListByZgjg(zgjgId);
        return gson.toJson(list);
    }

    @Transactional
    public String findYgListByZggs(Long zggsId) {
        Gson gson = new Gson();
        List list = this.ygDao.findYgListByZggs(zggsId);
        return gson.toJson(list);
    }

    /**
     * 查询员工明细
     *
     * @param id 员工id
     * @return
     */
    @Transactional
    public Yg findYgDetail(Long id) {
        return this.ygDao.get(id);
    }
    /**
     * 根据工号查询员工明细
     *
     * @param gh 员工id
     * @return
     */
    public Yg findBygh(String gh) {
        return this.ygDao.findUniqueByProperty("gh",gh);
    }

    /**
     * 员工导入电话号码调用的方法
     *
     * @param xm
     * @param zggs
     * @param zgjg
     * @return
     */
    @Transactional
    public Yg findYgByXm(String xm, String zggs, String zgjg) {
        return this.ygDao.findYgByXm(xm, zggs, zgjg);
    }

    /**
     * 员工导入电话号码时调用保存员工集合的方法
     *
     * @param ygList
     */
    @Transactional
    public void saveYgList(List<Yg> ygList) {
        for (Yg yg : ygList) {
            yg.setLastUpdated(new Date());
            this.ygDao.save(yg);
        }
    }


    /**
     * 查询员工所有的角色
     *
     * @param id 员工id
     * @return
     */
    @Transactional
    public List findYgAllJs(Long id) {
        return this.ygDao.findYgAllJs(id);
    }

    /**
     * 保存员工信息
     *
     * @param yg 员工实体
     * @return
     */
    @Transactional
    public void saveYg(Yg yg) throws RuntimeException {
        nullId(yg);
        if (this.ygDao.checkUnique(yg.getId(), "gh", yg.getGh())) {
            throw new RuntimeException("员工工号不能重复！");
        }
        if (this.ygDao.checkUnique(yg.getId(), "dlm", yg.getDlm().trim())) {
            throw new RuntimeException("员工登录名不能重复！");
        }
        if (this.ygDao.checkUnique(yg.getId(), "cwbh", yg.getCwbh())) {
            throw new RuntimeException("员工财务编号不能重复！");
        }
        //密码加密
        yg.setDlm(yg.getDlm().trim());
        yg.setDlmm(Md5.md5Encrypt16("111111"));
        yg.setDateCreated(new Date());
        yg.setLastUpdated(yg.getDateCreated());
        yg.setZggs(getZggs(yg.getZgjg()));
        this.ygDao.save(yg);
    }

    /**
     * 保存员工jiuqi信息
     *
     * @param yg 员工实体
     * @return
     */
    @Transactional
    public void saveYgJiuqiConform(Yg yg) throws RuntimeException {
        Yg y = this.ygDao.get(yg.getId());
        y.setLastUpdated(new Date());
        y.setJqdlm(yg.getJqdlm());
        y.setJqdlmm(yg.getJqdlmm());
        this.ygDao.save(y);
    }

    @Transactional
    public void saveYgkmdmys(Yg yg) {
        Yg y = ygDao.get(yg.getId());
        y.setKmdm(yg.getKmdm());
        ygDao.save(y);
    }

    /**
     * 保存员工信息
     *
     * @param yg 员工实体
     * @return
     */
    @Transactional
    public void updatePassword(Yg yg) throws RuntimeException {
        yg.setLastUpdated(new Date());
        this.ygDao.save(yg);
    }

    /**
     * 删除员工信息
     *
     * @param ygId 员工id
     * @return
     */
    @Transactional
    public void deleteYg(Long ygId) {
        Yg yg = ygDao.get(ygId);
        if (yg.getYgList() == null || yg.getYgList().size() != 0)
            throw new RuntimeException("禁止删除！");
        if (yg.getBmjlList() == null || yg.getBmjlList().size() != 0)
            throw new RuntimeException("禁止删除！");
        if (yg.getRcglList() == null || yg.getRcglList().size() != 0)
            throw new RuntimeException("禁止删除！");
        yg.setLastUpdated(new Date());
        yg.setDeleted(1);
        this.ygDao.save(yg);
    }

    /**
     * 更新员工信息
     *
     * @param yg 员工实体
     * @return
     */
    @Transactional
    public void updateYg(Yg yg) throws RuntimeException {
        nullId(yg);
        if (this.ygDao.checkUnique(yg.getId(), "gh", yg.getGh())) {
            throw new RuntimeException("员工工号不能重复！");
        }
        if (this.ygDao.checkUnique(yg.getId(), "dlm", yg.getDlm())) {
            throw new RuntimeException("员工登录名不能重复！");
        }
        if (this.ygDao.checkUnique(yg.getId(), "cwbh", yg.getCwbh())) {
            throw new RuntimeException("员工财务编号不能重复！");
        }
        Yg y = this.ygDao.get(yg.getId());
        y = (Yg) ReflectionUtils.getInstance(y, yg, new String[]{"deleted", "dateCreated", "lastUpdated", "dlmm", "jqdlm", "jqdlmm", "kmdm"});
        y.setLastUpdated(new Date());
        y.setZggs(getZggs(y.getZgjg()));
        this.ygDao.save(y);
    }

    private void nullId(Yg yg) {
        if (yg != null && yg.getZssj() != null && yg.getZssj().getId() == null)
            yg.setZssj(null);
        if (yg != null && yg.getZgjg() != null && yg.getZgjg().getId() == null)
            yg.setZgjg(null);
        if (yg != null && yg.getZygw() != null && yg.getZygw().getId() == null)
            yg.setZygw(null);
    }

    //获得主管公司
    public Gsjg getZggs(Gsjg gsjg) {
        if (gsjg == null) {
            return gsjg;
        }
        Gsjg temp = gsjgDao.get(gsjg.getId());
        if (temp.className().equals("Nbgs")) {
            return temp;
        } else {
            return getZggs(temp.getSjjg());
        }
    }

    @Transactional
    public void startYg(Long id) {
        Yg yg = ygDao.get(id);
        yg.setLastUpdated(new Date());
        yg.setKdl(true);
        this.ygDao.save(yg);
    }

    @Transactional
    public void stopYg(Long id) {
        Yg yg = ygDao.get(id);
        if (yg.getYgList() == null || yg.getYgList().size() != 0)
            throw new RuntimeException("禁止停用！");
        if (yg.getBmjlList() == null || yg.getBmjlList().size() != 0)
            throw new RuntimeException("禁止停用！");
        if (yg.getRcglList() == null || yg.getRcglList().size() != 0)
            throw new RuntimeException("禁止停用！");
        yg.setLastUpdated(new Date());
        yg.setKdl(false);
        this.ygDao.save(yg);
    }

    /**
     * ajax远程验证
     *
     * @param value 验证值
     * @param field 验证字段
     * @return
     */
    public boolean ajaxValidate(Long id, String value, Object field) {
        return ygDao.checkUnique(id, value, field);
    }

    /**
     * 获取下一个排序号
     *
     * @return
     */
    public Integer getNextPxh() {
        return ygDao.getMaxPxh() == null ? 0 : ygDao.getMaxPxh() + 1;
    }

    public static Map getYgSession() {
        ActionContext ctx = ActionContext.getContext();
        if (ctx.getSession() == null) {
            ActionContext.getContext().setSession(new HashMap());
        }
        return ctx.getSession();
    }


    //设置员工物资编码范围
    @Transactional
    public void savewzbmfw(List<String> kmysList, Long ygId) {
        String deleteSql = "delete from t_sys_yg_bmfw where yg_id = ?";
        ygDao.executeSQL(deleteSql, ygId);
        String insertSql = "";
        for (String kmys : kmysList) {
            if (StringUtils.isEmpty(kmys)) {
                continue;
            }
            String[] items = kmys.split(":");
            if (Long.valueOf(items[1]) == 1) {
                insertSql = "insert into t_sys_yg_bmfw select pm.id," + ygId + " from t_sys_pm pm" +
                        "  left join t_sys_bmb pmbm on pm.code = pmbm.bmz left join t_sys_rjwzbm rj on pm.rjwzbm_id = rj.id " +
                        "  left join t_sys_bmb rjbm on rjbm.bmz = rj.code left join t_sys_yjwzbm yj on rj.yjwzbm_id = yj.id" +
                        " where yj.id = ? and rj.deleted = 0 and pm.deleted = 0 and rjbm.zt = '1' and pmbm.zt = '1'";
            } else if (Long.valueOf(items[1]) == 2) {
                insertSql = "insert into t_sys_yg_bmfw select pm.id, " + ygId + " from t_sys_pm pm" +
                        "  left join t_sys_bmb pmbm on pm.code = pmbm.bmz left join t_sys_rjwzbm rj on pm.rjwzbm_id = rj.id " +
                        "where rj.id = ? and rj.deleted = 0 and pm.deleted = 0 and pmbm.zt = '1'";
            } else {
                insertSql = "insert into t_sys_yg_bmfw values(?," + ygId + ")";
            }
            ygDao.executeSQL(insertSql, Long.valueOf(items[0]));
        }
        String delRepeat = "delete from t_sys_yg_bmfw a where (a.pm_id, a.yg_id) in " +
                " (select pm_id, yg_id from t_sys_yg_bmfw group by pm_id, yg_id having count(1) > 1) " +
                "and rowid not in (select min(rowid) from t_sys_yg_bmfw group by pm_id, yg_id having count(1) > 1)";
        ygDao.executeSQL(delRepeat);
    }

    /**
     * 获得当前登陆的员工
     *
     * @return
     */
    public static Yg getCurrentYg() {
        Yg yg = new Yg();
        yg.setId((Long) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("id"));
        yg.setXm((String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("xm"));
        yg.setCxfw((Integer) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("cxfw"));

        Gsjg gsjg = new Gsjg();
        gsjg.setId((Long) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("jgid"));
        gsjg.setJc((String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("jgjc"));
        gsjg.setQc((String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("jgqc"));
        yg.setZgjg(gsjg);

        Gsjg zggs = new Gsjg();
        zggs.setId((Long) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("zggsid"));
        zggs.setBm((String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("zggsbm"));
        zggs.setJc((String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("zggsjc"));
        zggs.setQc((String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("zggsqc"));
        yg.setZggs(zggs);

        return yg;
    }


    /**
     * 获得员工的查询范围
     *
     * @return
     */
    public static Integer getCurrentYgCxfw() {
        return (Integer) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("cxfw");
    }

    /**
     * 获得当前登陆的员工的姓名
     *
     * @return
     */
    public static String getCurrentYgName() {
        return (String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("xm");
    }

    /**
     * 获得当前登陆的员工的机构名称
     *
     * @return
     */
    public static String getCurrentYgGs() {
        return (String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("jgjc");
    }

    /**
     * 获得当前登陆的员工的主管公司ID
     *
     * @return
     */
    public static Long getCurrentYgZgGsId() {
        return (Long) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("zggsid");
    }

    /**
     * 获得当前登陆的员工的主管公司CODE
     *
     * @return
     */
    public static String getCurrentYgZgGsCode() {
        return (String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("zggsbm");
    }

    /**
     * 获得当前登陆的员工的主管公司名称
     *
     * @return
     */
    public static String getCurrentYgZgGs() {
        return (String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("zggsjc");
    }

    /**
     * 获得当前登陆的员工的机构ID
     * ,
     *
     * @return
     */
    public static Long getCurrentYgGsId() {
        return (Long) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("jgid");
    }

    /**
     * 获得当前登陆的员工的权限ID
     *
     * @return
     */
    public static Set<Long> getCurrentYgQxId() {
        return (Set<Long>) getYgSession().get(AuthInterceptor.USER_ROLE_ID_SET_SESSION_KEY);
    }

    /**
     * 获得当前登陆的久其登陆名
     *
     * @return
     */
    public static String getCurrentYgJiuqiUsername() {
        return (String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("jqdlm");
    }

    /**
     * 获得当前登陆的久其登陆密码
     *
     * @return
     */
    public static String getCurrentYgJiuqiPassword() {
        return (String) ((Map) getYgSession().get(AuthInterceptor.USER_SESSION_KEY)).get("jqdlmm");
    }

    /**
     * 设置当前登录员工
     *
     * @param yg
     */
    public static void setCurrentUser(Map yg, Set<Long> roleList) {
        getYgSession().put(AuthInterceptor.USER_SESSION_KEY, yg);
        getYgSession().put(AuthInterceptor.USER_ROLE_ID_SET_SESSION_KEY, roleList);
    }

    /**
     * 清空员工session
     */
    public static void clearCurrentUser() {
        getYgSession().put(AuthInterceptor.USER_SESSION_KEY, null);
        getYgSession().put(AuthInterceptor.USER_ROLE_ID_SET_SESSION_KEY, null);
        getYgSession().clear();
    }

    /**
     * 密码重置
     */
    @Transactional
    public void resetYg(Long id) {
        Yg yg = ygDao.get(id);
        yg.setDlmm(Md5.md5Encrypt16("111111"));
        this.ygDao.save(yg);
    }

    /**
     * 获取员工科目代码
     */
    public String findKmdm(Long gsId) {
        Gson gson = new Gson();
        return gson.toJson(ygDao.findKmdm(gsId));
    }

    @Autowired
    public void setYgDao(YgDao ygDao) {
        this.ygDao = ygDao;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }
}
